package com.imarad.bio.socket.core;


import com.imarad.bio.socket.common.ClientPacket;

import org.apache.commons.lang3.StringUtils;

/**
 * Copyright2017-2017  AMBITION.All Rights Reserved
 * Socket使用工具
 * 使用步骤 1、manageKey = SocketClientUtils.init(SocketProperty, ConnectedCallback)
 * 2、SocketClientUtils.send(manageKey, ClientPacket);
 * 关闭：   3、SocketClientUtils.close(manageKey);
 * Comments：
 *
 * @author huh
 *
 *         Time: 2018/2/1
 *
 *         Modified By:
 *         Modified Date:
 *         Why & What is modified:
 * @version 1.0.0
 */
public class SocketClientUtils {

    /**
     * 初始化管理器
     *
     * @param socketProperty    连接属性
     * @param connectedCallback 连接回调
     * @return 连接器key
     */
    public static String init(SocketProperty socketProperty,
            ConnectedCallback connectedCallback) {
        if (socketProperty == null) {
            throw new SocketClientException("null SocketProperty");
        }
        if (StringUtils.isEmpty(socketProperty.getHost())) {
            throw new SocketClientException("null HostAddress");
        }
        if (socketProperty.getPort() <= 0) {
            throw new SocketClientException("error port");
        }
        return SocketManageFactory.connect(socketProperty, connectedCallback);
    }

    /**
     * 通过socket发送数据
     * 返回消息通过注册的回调执行:
     *
     * @param manageKey    socket管理类键值
     * @param clientPacket 发送数据包
     * @see ConnectedCallback#writeSuccess(ClientPacket)
     */
    public static void send(String manageKey, ClientPacket clientPacket) {
        checkManageKey(manageKey);
        SocketManageFactory.getSocketManager(manageKey).sendData(clientPacket);
    }

    /**
     * 关闭连接
     *
     * @param manageKey 管理器键值
     */
    public static void close(String manageKey) {
        checkManageKey(manageKey);
        SocketManageFactory.disConnect(manageKey);
    }

    /**
     * 检查管理器键值
     *
     * @param manageKey 管理器键值
     */
    private static void checkManageKey(String manageKey) {
        if (StringUtils.isEmpty(manageKey)) {
            throw new SocketClientException("The manageKey is the most important in this Method");
        }
    }
}